/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jsrpc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jsrpc.bridge.Broker;
import org.jsrpc.bridge.Key;
import org.jsrpc.core.ClassSupportHandler;

/**
 *
 * @author neo
 */
public class BrokerServlet extends HttpServlet {

    static final String UTF8 = "UTF-8";
    private static final long serialVersionUID = -3328998084308489216L;
    Logger log = Logger.getLogger(this.getClass().getName());
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        log.info("Call Register.");
        response.setContentType("text/plain;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Properties prop = new Properties();
        StringBuilder s = new StringBuilder();
        try {
            prop.load(getClass().getResourceAsStream("/configure.properties"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        String pageId = request.getParameter("pageId");
        try {
            HttpSession session = request.getSession();
            List<Broker> listServices = (List<Broker>) session.getAttribute(Key.REMOTE_REGISTER+"."+pageId);
            for (int index = 0; index < listServices.size(); index++) {
                Broker broker = listServices.get(index);
                String serviceName = broker.getId();
                String serviceClassName = broker.getBean();
                s.append(serviceName).append(" = {\n");
                Object obj = Class.forName(serviceClassName).newInstance();
                Method[] methods = obj.getClass().getDeclaredMethods();
                for (int i = 0; i < methods.length; i++) {
                    Method method = methods[i];
                    s.append("\t").append(method.getName()).append(": function(");
                    StringBuffer spf = new StringBuffer();
                    StringBuilder sm = new StringBuilder();
                    //sm.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                    sm.append("{");
                    sm.append("javaClass:").append(serviceClassName).append(",");
                    sm.append("method:").append(method.getName()).append(",");

                    Class[] cp = method.getParameterTypes();

                    sm.append("length:");
                    if (cp != null) {
                        sm.append(cp.length);
                        if (cp.length > 0) { //edit now
                            sm.append(",");
                        }
                    } else {
                        sm.append("0");
                    }
                    for (int j = 0; j < cp.length; j++) {
                        Class class1 = cp[j];
                        //System.out.print("Object name Support["+ class1.getName() +"]");
                        String ptype = prop.getProperty(class1.getName() + ".ptype");
                        if (ptype != null) {
                            sm.append("param_").append(j).append(":{");
                            sm.append("javaClass:").append(class1.getName()).append(",");
                            sm.append("value:\"+").append("param_").append(j).append("+\"");
                            s.append("param_").append(j);
                            //if (j < (cp.length - 1)) {
                                //s.append(",");
                            //}
                            sm.append("}");
                        } else {
                            s.append("param_").append(j);
                            String classSupport = prop.getProperty(class1.getName() + ".support");
                            if (classSupport == null) {
                                classSupport = prop.getProperty("default.support");
                                try {
                                    ClassSupportHandler supportHandle = (ClassSupportHandler) Class.forName(classSupport).newInstance();
                                    sm.append(supportHandle.handle(prop, j, method, class1));
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            } else {
                                sm.append("param_").append(j).append(":{");
                                sm.append("javaClass:").append(class1.getName()).append(",");
                                sm.append("value:\"+").append("buf_").append(j).append(".toString()+\"");
                                try {
                                    ClassSupportHandler supportHandle = (ClassSupportHandler) Class.forName(classSupport).newInstance();
                                    spf.append(supportHandle.handle(prop, j, method, class1));
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                                sm.append("}");
                            }
                            
                        }
                        if (j < (cp.length - 1)) {
                            sm.append(",");
                            s.append(",");
                        }
                    }
                    sm.append("}");
                    if( s.toString().endsWith(",") ) {
                        s.delete(s.length()-1, s.length());
                    }
                    s.append(") {\n");
                    s.append(spf);
                    s.append("\t\tvar httpRequest = new HttpRequest();\n");
                    String prefixPath = (String)session.getAttribute("BACK_PATH."+pageId);
                    s.append("\t\thttpRequest.setUrl(\"").append(prefixPath).append("JS-RPC\");\n");
                    s.append("\t\thttpRequest.setSubmit(encodeURI(\"").append(sm.toString()).append("\"));\n");
                    s.append("\t\tvar re = httpRequest.synchronize();\n");
                    Class reClass = method.getReturnType();
                    String ptype = prop.getProperty(reClass.getName() + ".ptype");
                    if (ptype == null) {
                        s.append("\t\teval(re);\n");
                        s.append("\t\treturn reObj;\n");
                    } else {
                        s.append("\t\treturn re;\n");
                    }
                    s.append("\t}\n");
                    if (i < (methods.length - 1)) {
                        s.append(",\n");
                    }
                    sm.delete(0, sm.length());
                }
                s.append("};\n");
            }
            log.info("Send Objec["+ s.toString() +"]");
            log.info("Send object broker.");
            
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            request.getSession().removeAttribute(Key.REMOTE_REGISTER+"."+pageId);
            request.getSession().removeAttribute("BACK_PATH."+pageId);
            out.println(s.toString());
            out.close();
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
